package com.bdqn.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.mapper.RightMapper;
import com.bdqn.pojo.Right;
import com.bdqn.service.RightService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 权限Service实现
 *
 * @author LILIBO
 * @since 2024/09/07
 */
@Service
public class RightServiceImpl extends ServiceImpl<RightMapper, Right> implements RightService {

    @Resource
    private RightMapper rightMapper;

    /**
     * 获取所有权限信息
     *
     * @return
     */
    @Override
    @Cacheable(value = "right", key = "'all'", unless = "#result==null")
    public List<Right> findAll() {
        return super.list();
    }

    /**
     * 根据角色ID获取权限集合
     *
     * @param roleId
     * @return
     */
    @Override
    @Cacheable(value = "right", key = "'roleId:'+#roleId", condition = "#roleId != null", unless = "#result==null")
    public Set<Right> findRightByRoleId(Long roleId) {
        return rightMapper.findRightByRoleId(roleId);
    }

    /**
     * 动态加载授权信息
     *
     * @return
     */
    @Override
    public Map<String, String> loadFilterChainDefinitions() {

        // 权限配置集合，必须使用LinkedHashMap(有序集合)
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();

        // 静态资源授权
        filterChainDefinitionMap.put("/css/**", "anon");
        filterChainDefinitionMap.put("/fonts/**", "anon");
        filterChainDefinitionMap.put("/images/**", "anon");
        filterChainDefinitionMap.put("/js/**", "anon");
        filterChainDefinitionMap.put("/localcss/**", "anon");
        filterChainDefinitionMap.put("/localjs/**", "anon");

        // API接口请求授权
        filterChainDefinitionMap.put("/api/**", "anon");

        // 登录退出页面设置
        filterChainDefinitionMap.put("/login", "anon"); // 点击登录按钮时放行
        filterChainDefinitionMap.put("/logout", "logout"); // 点击退出按钮时放行

        // 配置需要特定权限才能访问的资源(URL)
        // 静态授权：包括全部需要特定权限才能访问的资源(URL)
        /*
        filterChainDefinitionMap.put("/user/list", "perms[用户列表]");
        filterChainDefinitionMap.put("/user/add", "perms[用户添加]");
        filterChainDefinitionMap.put("/user/edit", "perms[用户编辑]");
        filterChainDefinitionMap.put("/user/del", "perms[用户删除]");
        */

        // 动态授权
        List<Right> rights = this.findAll();
        for (Right right : rights) {
            if (right.getRightUrl() != null && !right.getRightUrl().trim().isEmpty()) {
                filterChainDefinitionMap.put(right.getRightUrl(), "perms[" + right.getRightCode() + "]");
            }
        }

        // 配置认证访问：其他资源(URL)必须认证通过才能访问
        filterChainDefinitionMap.put("/**", "authc"); // 必须放在过滤器链的最后面

        return filterChainDefinitionMap;
    }

    /**
     * 重新加载动态权限
     */
    @Override
    public boolean reloadFilterChainDefinitions() {
        // 重新加载动态权限，配置权限验证规则
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            ServletContext servletContext = request.getSession().getServletContext();
            AbstractShiroFilter shiroFilter = (AbstractShiroFilter) WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext).getBean("shiroFilterFactory");
            synchronized (shiroFilter) {
                // 获取过滤管理器
                PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
                DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();
                // 清空初始权限配置
                manager.getFilterChains().clear();
                // 重新加载动态权限，配置权限验证规则
                Map<String, String> chains = loadFilterChainDefinitions();
                // System.out.println("chains-------"+chains);
                for (Map.Entry<String, String> entry : chains.entrySet()) {
                    String url = entry.getKey();
                    String chainDefinition = entry.getValue().trim().replace(" ", "");
                    manager.createChain(url, chainDefinition);
                }
                System.out.println("更新权限成功！");
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}




